﻿using BLL;
using System;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Thksoft.Module.DataDetail
{
    public partial class MonthCapital : BaseUI.BasePage
    {
        private Sys_CompanyBLL companyBLL = new Sys_CompanyBLL();
        private QS_PLANMONTHAPPLYBLL planMonthApplyBLL = new QS_PLANMONTHAPPLYBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                txtDate.Value = DateTime.Now.Year.ToString();
            }
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            var orderStr = ViewState["ORDER"] as string;
            var orderTypeStr = ViewState["ORDER_TYPE"] as string;
            if (txtDate.Value.Trim() == "")
            {
                MessageBox.Show(Page, "请选择计划年！");
                return;
            }

            int year = int.Parse(txtDate.Value.Substring(0, 4));
            decimal comid = lognUser.USER_COMPANY;
            if (ddlCom.Value != -1)
            {
                comid = ddlCom.Value;
            }
            var comidStr = companyBLL.GetCompanyFatherAndChildByID(comid);
            var sql = @"SELECT
	T1.N_MONTHAPP_ID,
	T1.N_BUSINESS_ID,
	T2.CMY_NAME,
	T1.C_MONTH_NAME,
	T1.N_MONTH,
	SUM(decode(T4.N_TYPE2,1,T3.N_AMOUNT,0)) INTO_SUM,
	SUM(decode(T4.N_TYPE2,2,T3.N_AMOUNT,0)) OUT_SUM
FROM QS_PLANMONTHAPPLY T1
INNER JOIN SYS_COMPANY T2
ON T1.N_COMPANY_ID = T2.CMY_ID
INNER JOIN QS_PLANMONTH_DETAIL T3
ON T1.N_MONTHAPP_ID = T3.N_MONTHAPP_ID
INNER JOIN QS_PROJECT T4
ON T3.N_PROID = T4.N_PROID
WHERE T1.N_COMPANY_ID IN ({0}) AND T4.N_TYPE = 2 {1}
GROUP BY
	T1.N_MONTHAPP_ID,
	T1.N_BUSINESS_ID,
	T2.CMY_NAME,
	T1.C_MONTH_NAME,
	T1.N_MONTH "; //T1.N_MONTH

            if (orderStr != null)
            {
                sql += " ORDER BY " + orderStr + " " + orderTypeStr;
            }

            sql = string.Format(sql, comidStr, "AND T1.N_YEAR = " + year);

            DataTable dt = planMonthApplyBLL.Query(sql);
            var row = dt.NewRow();
            row["CMY_NAME"] = "合计";
            row["N_MONTHAPP_ID"] = DBNull.Value;
            row["N_BUSINESS_ID"] = 0;
            row["C_MONTH_NAME"] = DBNull.Value;
            row["INTO_SUM"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["INTO_SUM"]));
            row["OUT_SUM"] = dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["OUT_SUM"]));
            dt.Rows.Add(row);
            grvShow1.DataSource = dt;
            grvShow1.DataBind();
        }

        protected void grvShow_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string buid = ((Label)e.Row.FindControl("lblBuid")).Text;
                if (buid == "0")
                {
                    ((Panel)e.Row.FindControl("Panel2")).Visible = false;
                }
            }
        }

        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvShow1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["ORDER"] == null ? null : (string)ViewState["ORDER"];
            OrderDire = ViewState["ORDER_TYPE"] == null ? null : (string)ViewState["ORDER_TYPE"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "DESC")
                    OrderDire = "ASC";
                else
                    OrderDire = "DESC";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["ORDER"] = SortOrder;
            ViewState["ORDER_TYPE"] = OrderDire;
            btnSelect_Click(sender, e);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrint_Click1(object sender, EventArgs e)
        {
            var orderStr = ViewState["ORDER"] as string;
            var orderTypeStr = ViewState["ORDER_TYPE"] as string;

            if (txtDate.Value == "" || grvShow1 == null || grvShow1.Rows.Count == 0)
            {
                MessageBox.Show(Page, "【系统提示】未能查询出数据，暂时不能导出，请先查询数据。");
                return;
            }

            int year = int.Parse(txtDate.Value.Substring(0, 4));
            decimal comid = lognUser.USER_COMPANY;
            if (ddlCom.Value != -1)
            {
                comid = ddlCom.Value;
            }
            var comidStr = companyBLL.GetCompanyFatherAndChildByID(comid);

            var sql = @"SELECT
	T1.N_MONTHAPP_ID,
	T1.N_BUSINESS_ID,
	T2.CMY_NAME,
	T1.C_MONTH_NAME,
	T1.N_MONTH,
	SUM(decode(T4.N_TYPE2,1,T3.N_AMOUNT,0)) INTO_SUM,
	SUM(decode(T4.N_TYPE2,2,T3.N_AMOUNT,0)) OUT_SUM
FROM QS_PLANMONTHAPPLY T1
INNER JOIN SYS_COMPANY T2
ON T1.N_COMPANY_ID = T2.CMY_ID
INNER JOIN QS_PLANMONTH_DETAIL T3
ON T1.N_MONTHAPP_ID = T3.N_MONTHAPP_ID
INNER JOIN QS_PROJECT T4
ON T3.N_PROID = T4.N_PROID
WHERE T1.N_COMPANY_ID IN ({0}) AND T3.N_TYPE=2 {1}
GROUP BY
	T1.N_MONTHAPP_ID,
	T1.N_BUSINESS_ID,
	T2.CMY_NAME,
	T1.C_MONTH_NAME,
	T1.N_MONTH "; //T1.N_MONTH

            if (orderStr != null)
            {
                sql += " ORDER BY " + orderStr + " " + orderTypeStr;
            }

            sql = string.Format(sql, comidStr, "AND T1.N_YEAR = " + year);

            DataTable dt = planMonthApplyBLL.Query(sql);

            var html = "<table border='1'>";
            html += "<tr>";
            html += "<th>公司名称</th>";
            html += "<th>业务名称</th>";
            html += "<th>月数</th>";
            html += "<th>合计（流入）</th>";
            html += "<th>合计（流出）</th>";
            html += "</tr>";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                html += "<tr>";

                if (i % 2 == 0)
                {
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["CMY_NAME"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["C_MONTH_NAME"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["N_MONTH"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["INTO_SUM"].ToString() + "</td>";
                    html += "<td style=\"background-color:#EAFFFF;\">" + dt.Rows[i]["OUT_SUM"].ToString() + "</td>";
                }
                else
                {
                    html += "<td>" + dt.Rows[i]["CMY_NAME"].ToString() + "</td>";
                    html += "<td>" + dt.Rows[i]["C_MONTH_NAME"].ToString() + "</td>";
                    html += "<td>" + dt.Rows[i]["N_MONTH"].ToString() + "</td>";
                    html += "<td>" + dt.Rows[i]["INTO_SUM"].ToString() + "</td>";
                    html += "<td>" + dt.Rows[i]["OUT_SUM"].ToString() + "</td>";
                }

                html += "</tr>";
            }

            html += "<tr>";
            html += "<td colspan=\"3\" align=\"center\">合计</td>";
            html += "<td>" + dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["INTO_SUM"])) + "</td>";
            html += "<td>" + dt.AsEnumerable().Sum(a => Convert.ToDecimal(a["OUT_SUM"])) + "</td>";
            html += "<td></td>";
            html += "</tr>";
            html += "</table>";
            toExecl1(html, (txtDate.Value == "" ? "" : txtDate.Value + "月") + "资金明细");
        }
    }
}